<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件传输服务器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
</head>

<body class="bg-gray-100 flex justify-center items-center h-screen">
    <div class="bg-white p-8 rounded shadow-md w-96">
        <div class="flex justify-between items-center mb-6">
            
            <div class="flex items-center space-x-2">
                <i class="fa fa-upload text-green-500 text-2xl mr-2" aria-hidden="true"></i>
            <h2 class="text-2xl font-bold">文件投送</h2>
            </div>
            <!-- <a href="/browser" class="text-blue-500 hover:text-blue-700 text-sm flex items-center">
                <i class="fa fa-folder-open mr-1"></i> 文件拿取
            </a> -->
            <a href="/browser" class="flex items-center px-4 py-2 bg-blue-500 text-white rounded-md">
                <i class="fa fa-upload mr-2"></i> 文件拿取
            </a>
        </div>
        
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="mb-4">
                <label for="textInput" class="block text-sm font-medium text-gray-700">你是谁？</label>
                <input type="text" id="textInput" name="textInput" required
                    class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
            </div>
            <div class="mb-4">
                <label for="files" class="block text-sm font-medium text-gray-700">选择文件</label>
                <input type="file" id="files" name="files" multiple
                    class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
            </div>
            <button type="submit" id="submitBtn"
                class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                上传！
            </button>
        </form>
        
        <!-- 进度条容器 -->
        <div id="progressContainer" class="mt-4 hidden">
            <div class="flex justify-between mb-1">
                <span class="text-sm font-medium text-gray-700" id="progressStatus">准备上传...</span>
                <span class="text-sm font-medium text-gray-700" id="progressPercent">0%</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2.5">
                <div id="progressBar" class="bg-blue-600 h-2.5 rounded-full" style="width: 0%"></div>
            </div>
            <div class="text-xs text-gray-500 mt-1" id="fileInfo"></div>
        </div>

        <div id="result" class="mt-4"></div>
    </div>

    <script>
        const form = document.getElementById('uploadForm');
        const resultDiv = document.getElementById('result');
        const textInput = document.getElementById('textInput');
        const submitBtn = document.getElementById('submitBtn');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const progressPercent = document.getElementById('progressPercent');
        const progressStatus = document.getElementById('progressStatus');
        const fileInfo = document.getElementById('fileInfo');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(form);
            

            
            // console.log(files);
            
            // files.forEach(element => {
            //     console.log(element);
            // });
            
            // 删除上次结果信息
            resultDiv.innerHTML = '';
            
            // 获取文件信息
            const files = document.getElementById('files').files;
            console.log('前端原始文件名:', Array.from(files).map(f => f.name)); // 验证原始名称
            // console.log(files);
                
            const totalSize = Array.from(files).reduce((acc, file) => acc + file.size, 0);
            let uploadedSize = 0;
            
            // 显示进度条
            progressContainer.classList.remove('hidden');
            submitBtn.disabled = true;
            submitBtn.classList.add('opacity-50');
            
            // 更新文件信息
            fileInfo.textContent = `正在上传 ${files.length} 个文件 (${formatFileSize(totalSize)})`;
            
            try {
                const xhr = new XMLHttpRequest();
                
                // 进度事件
                xhr.upload.addEventListener('progress', (event) => {
                    if (event.lengthComputable) {
                        const percent = Math.round((event.loaded / event.total) * 100);
                        progressBar.style.width = `${percent}%`;
                        progressPercent.textContent = `${percent}%`;
                        progressStatus.textContent = `上传中...`;
                        
                        // 更新已上传大小
                        uploadedSize = event.loaded;
                        fileInfo.textContent = `正在上传 ${files.length} 个文件 (${formatFileSize(uploadedSize)}/${formatFileSize(totalSize)})`;
                    }
                });
                
                // 完成事件
                xhr.addEventListener('load', () => {
                    if (xhr.status === 200) {
                        const data = JSON.parse(xhr.responseText);
                        resultDiv.innerHTML = `<p class="text-green-500">OK，${textInput.value}，${data.message}</p>`;
                        progressStatus.textContent = '上传完成';
                        
                        // // 3秒后跳转到文件浏览器
                        // setTimeout(() => {
                        //     window.location.href = '/browser';
                        // }, 3000);
                    } else {
                        const error = JSON.parse(xhr.responseText);
                        resultDiv.innerHTML = `<p class="text-red-500">Oh no，${textInput.value}，${error.message}</p>`;
                        progressStatus.textContent = '上传失败';
                    }
                    submitBtn.disabled = false;
                    submitBtn.classList.remove('opacity-50');
                });
                
                // 错误事件
                xhr.addEventListener('error', () => {
                    resultDiv.innerHTML = `<p class="text-red-500">网络错误，请重试</p>`;
                    progressStatus.textContent = '上传失败';
                    progressBar.classList.remove('bg-blue-600');
                    progressBar.classList.add('bg-red-500');
                    submitBtn.disabled = false;
                    submitBtn.classList.remove('opacity-50');
                });
                
                // 中止事件
                xhr.addEventListener('abort', () => {
                    resultDiv.innerHTML = `<p class="text-yellow-500">上传已取消</p>`;
                    progressStatus.textContent = '上传已取消';
                    progressBar.classList.remove('bg-blue-600');
                    progressBar.classList.add('bg-yellow-500');
                    submitBtn.disabled = false;
                    submitBtn.classList.remove('opacity-50');
                });
                
                xhr.open('POST', '/api/upload');
                xhr.send(formData);
                
            } catch (error) {
                resultDiv.innerHTML = `<p class="text-red-500">服务器崩了: ${error.message}</p>`;
                progressStatus.textContent = '上传失败';
                progressBar.classList.remove('bg-blue-600');
                progressBar.classList.add('bg-red-500');
                submitBtn.disabled = false;
                submitBtn.classList.remove('opacity-50');
            }
        });
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>

</html>    